#include "usermodel.hpp"
#include "mysql.hpp"
#include <iostream>
#include <string>
using namespace std;
UserModel::UserModel()
{
}

UserModel::~UserModel()
{
}
bool UserModel::Insert(User& user) {
    // 插入成功后返回id
    char sql[1024]{0};
    sprintf(sql, "INSERT INTO user(name, password, state) VALUES ('%s', '%s', '%s')", user.getName().c_str(), user.getPassword().c_str(), user.getState().c_str());
    MySql mysql;
    bool ret = mysql.connect();
    if (!ret) {
        return false;
    }
    ret = mysql.update(sql);
    if (!ret) return false;
    const auto id = mysql_insert_id(mysql.GetConection());
    user.setId(id);
    return true;
}
User UserModel::Query(int id) {
    char sql[1024]{0};
    sprintf(sql, "SELECT * FROM user WHERE id = %d", id);
    MySql mysql;
    mysql.connect();
    MYSQL_RES *res = mysql.query(sql);
    do {
        if (res == nullptr) break;
        MYSQL_ROW row = mysql_fetch_row(res);
        if (row == nullptr) break;
        const int id = stoi(row[0]);
        const string name = row[1];
        const string password = row[2];
        const string state = row[3];
        return User(id, name, password, state);
    } while (0);
    return {};
}
void UserModel::UpdateState(User& user, std::string state) {
    user.setState(state);
    char sql[1024]{0};
    const int id = user.getId();
    sprintf(sql, "UPDATE user SET state = '%s' WHERE id = %d", state.c_str(), id);
    MySql mysql;
    mysql.connect();
    mysql.update(sql);
}// {"msgId": 0, "id": 13, "password": "123456"}

void UserModel::Reset() {
    char sql[1024]{0};
    sprintf(sql, "UPDATE user SET state = 'offline' WHERE state = 'online'");
    MySql mysql;
    if (mysql.connect()) {
        mysql.update(sql);
    }
}